import { PenChildProps } from "@/types";
import { Input, Space, Tag } from "antd";
import React, { ChangeEvent, useState } from "react";
import { CloseCircleOutlined } from "@ant-design/icons";
import { deepClone } from "@meta2d/core";
export function DataAddTag({ penOptions, setPenValue }: PenChildProps) {
  const [value, setValue] = useState<string>("");
  const onChange = (e: ChangeEvent<HTMLInputElement>) => {
    setValue(() => e.target.value);
  };
  const handleAdd = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key == "Enter" && value != "") {
      let newList = [value];
      if (penOptions.tags != undefined) {
        newList = [value, ...penOptions.tags];
      }
      setPenValue("tags", newList);
      setValue(() => "");
    }
  };
  const handleDel = (
    e: React.MouseEvent<HTMLElement, MouseEvent>,
    index: number,
  ) => {
    e.preventDefault();
    let newList = deepClone(penOptions.tags) || [];
    newList.splice(index, 1);
    setPenValue("tags", newList);
  };

  return (
    <div style={{ padding: 10 }}>
      <Space wrap style={{ marginBottom: 10 }}>
        {penOptions.tags &&
          penOptions.tags.map((item, index) => {
            return (
              <Tag
                onClose={(e) => handleDel(e, index)}
                key={"dataTag" + index}
                closeIcon={<CloseCircleOutlined />}
              >
                {item}
              </Tag>
            );
          })}
      </Space>
      <Input
        value={value}
        placeholder={"按回车添加"}
        maxLength={20}
        onKeyDown={handleAdd}
        onChange={onChange}
      ></Input>
    </div>
  );
}
